package ecweb.ui.order;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ecweb.domain.Order;
import ecweb.domain.User;
import ecweb.domain.dto.TCartItemDetail;
import ecweb.domain.dto.TGoodItemAndQuantity;
import ecweb.exception.DatabaseException;
import ecweb.service.ICartService;
import ecweb.service.IOrderService;
import ecweb.service.impl.CartService;
import ecweb.service.impl.OrderService;
import util.web.page.PageBean;

/**
 * Servlet implementation class CreateOrderServlet
 */
@WebServlet("/Order/CreateOrder")
public class CreateOrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private ICartService cartService = new CartService();
	private IOrderService orderService = new OrderService();
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreateOrderServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		
		User user = (User) session.getAttribute("user");
		if (user == null) {
			response.sendRedirect(request.getContextPath() + "/Account/Login");
			return;
		}
		
		response.sendRedirect(request.getContextPath() + "/Cart/ShowMyCart");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");
		if ("confirm".equals(action)) {
			doConfirm(request, response);
		} else if ("create".equals(action)) {
			doCreate(request, response);
		} else {
			response.sendError(403);
			return;
		}
	}

	private void doConfirm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		
		User user = (User) session.getAttribute("user");
		if (user == null) {
			response.sendRedirect(request.getContextPath() + "/Account/Login");
			return;
		}

		LinkedList<TGoodItemAndQuantity> gooditemAndQuantityList = new LinkedList<>();
		String strData = request.getParameter("data");
		for (String eachData : strData.split("\\|")) {
			String[] eachElement = eachData.split(",");
			if (eachElement.length != 2) {
				continue;
			}
			TGoodItemAndQuantity gooditemAndQuantity = new TGoodItemAndQuantity();
			try {
				gooditemAndQuantity.setGoodId(Long.parseLong(eachElement[0]));
				gooditemAndQuantity.setQuantity(Integer.parseInt(eachElement[1]));
			} catch (NumberFormatException e) {
				continue;
			}
			gooditemAndQuantityList.add(gooditemAndQuantity);
		}
		
		List<TCartItemDetail> cartItemDetailList = null;
		try {
			cartItemDetailList = cartService.transformToCartItemDetailList(user.getId(), gooditemAndQuantityList);
		} catch (DatabaseException e) {
			response.sendError(500);
			return;
		}
		
		double totalTransactionPrice = 0d;
		for (TCartItemDetail each : cartItemDetailList) {
			totalTransactionPrice += each.getTotalPrice();
		}
		request.setAttribute("totalTransactionPrice", totalTransactionPrice);
		
		PageBean<TCartItemDetail> page = new PageBean<>();
		page.setCurrentPage(0);
		page.setPageSize(cartItemDetailList.size());
		page.setRecords(cartItemDetailList, cartItemDetailList.size());
		request.setAttribute("page", page);
		
		String orderConfirmPostData = "";
		StringBuffer sBuffer = new StringBuffer();
		for (TCartItemDetail eachItem : page.getRecords()) {
			sBuffer.append(eachItem.getGoodItem().getId())
					.append(',')
					.append(eachItem.getCartItem().getQuantity())
					.append("|");
		}
		if (sBuffer.length() != 0 && sBuffer.charAt(sBuffer.length() - 1) == '"')
			orderConfirmPostData = sBuffer.substring(0, sBuffer.length() - 1);
		else
			orderConfirmPostData = sBuffer.toString();
		request.setAttribute("orderConfirmPostData", orderConfirmPostData);
		
		request.getRequestDispatcher("confirm_order.jsp").forward(request, response);
	}

	private void doCreate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		
		User user = (User) session.getAttribute("user");
		if (user == null) {
			response.sendRedirect(request.getContextPath() + "/Account/Login");
			return;
		}

		List<TGoodItemAndQuantity> gooditemAndQuantityList = new LinkedList<TGoodItemAndQuantity>();
		String strData = request.getParameter("data");
		for (String eachData : strData.split("\\|")) {
			String[] eachElement = eachData.split(",");
			if (eachElement.length != 2) {
				continue;
			}
			TGoodItemAndQuantity gooditemAndQuantity = new TGoodItemAndQuantity();
			try {
				gooditemAndQuantity.setGoodId(Long.parseLong(eachElement[0]));
				gooditemAndQuantity.setQuantity(Integer.parseInt(eachElement[1]));
			} catch (NumberFormatException e) {
				continue;
			}
			gooditemAndQuantityList.add(gooditemAndQuantity);
		}
		
		List<TCartItemDetail> cartItemDetailList = null;
		try {
			cartItemDetailList = cartService.transformToCartItemDetailList(user.getId(), gooditemAndQuantityList);
		} catch (DatabaseException e) {
			response.sendError(500);
			return;
		}
		
		gooditemAndQuantityList = cartService.transformToGoodItemAndQuantityList(cartItemDetailList);
		
		Order order = null;
		try {
			order = orderService.createOrder(user.getId(), gooditemAndQuantityList);
			cartService.subQuantity(user.getId(), gooditemAndQuantityList);
		} catch (IllegalArgumentException e) {
			response.sendError(403);
			return;
		} catch (DatabaseException e) {
			response.sendError(500);
			return;
		}
		
		response.sendRedirect(request.getContextPath() + "/Order/ShowOrderDetail?id=" + order.getId());
	}
}
